<template>
  <!-- 手机号登录页面 -->
  <Vcode :show="Show" @success="success" @close="close" @fail="fail"></Vcode>
  <div>
    <el-form
      ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <el-form-item prop="namea">
        <div class="flex labelClass margin-bottom">
          <img src="../assets/images/login/qiye.png" alt="" />
          <el-input
            disabled
            :input-style="{
              boxShadow: 'none',
            }"
            v-model="loginForm.namea"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="工厂编号"
          />
        </div>
      </el-form-item>
      <el-form-item prop="phoneNumber">
        <div class="flex labelClass margin-bottom">
          <img
            class="iponeimg"
            src="../assets/images/login/手机号码.png"
            alt=""
          />
          <el-input
            :input-style="{
              boxShadow: 'none',
            }"
            v-model="loginForm.phoneNumber"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="手机号"
          />
        </div>
      </el-form-item>
      <el-form-item prop="smsCode">
        <div class="flex labelClass margin-bottom">
          <img
            class="iponeimg"
            src="../assets/images/login/验证码.png"
            alt=""
          />
          <div class="inputButton">
            <el-input
              :input-style="{
                boxShadow: 'none',
              }"
              v-model="loginForm.smsCode"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="验证码"
            />
            <el-button
              type="text"
              class="CodeButton"
              size="large"
              @click="giveCode"
              :disabled="num != 0"
            >
              {{ num == 0 ? "获取验证码" : `${num}秒后重新发送` }}</el-button
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item style="margin: 0px 0px 25px 0px">
        <el-checkbox
          v-model="loginForm.x"
          label=""
          true-label="1"
          false-label="2"
        />
        <el-link>&nbsp;我已阅读并同意《xxx》</el-link>
      </el-form-item>
      <el-form-item style="width: 100%; margin-top: 55px">
        <el-button
          :loading="iponeloading"
          size="large"
          type="primary"
          style="width: 100%"
          @click.prevent="handleLogin"
        >
          <span v-if="!iponeloading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="display: flex; align-items: center" v-if="!register">
          <router-link type="primary" class="link-type" :to="'/register'"
            >立即注册</router-link
          >
          <el-divider direction="vertical" />

          <router-link type="primary" class="link-type" :to="'/forgotPwd'"
            >忘记密码</router-link
          >
          <el-divider direction="vertical" />
          <AppQcode />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {
  getCodeAPI,
  checkSmsCodeAPI,
  getIsRegistrationAPI,
} from "@/api/system/user.js";
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { useRoute, useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";
import Vcode from "vue3-puzzle-vcode";
import AppQcode from "./appQcode.vue";
const to = () => {
  window.open("https://www.pureut.com/");
};
const Show = ref(false);
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const isShowDialog = ref(false);
const loginForm = ref({
  phoneNumber: "",
  smsCode: "",
  x: "",
});

const loginRules = {
  phoneNumber: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
  ],
  smsCode: [{ required: true, trigger: "blur", message: "请输入您的验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

//手机号登录
async function handleLogin() {
  if (loginForm.value.x != "1")
    return proxy.warningMsg("请先勾选我已阅读并同意xxx协议!!!");
  proxy.$refs.loginRef.validate(async (valid) => {
    if (valid) {
      const result = await getIsRegistrationAPI(loginForm.value);
      if (result?.data && result.data.isStatus != "2")
        return router.push(`/InitializeForm?id=${loginForm.value.phoneNumber}`);
      //验证验证码是否正确，如果后端返回code不是200return后端给的信息
      const res = await checkSmsCodeAPI({
        phoneNumber: loginForm.value.phoneNumber,
        smsCode: loginForm.value.smsCode,
      });
      if (res.code != 200) return proxy.warningMsg(`${res.msg}`);
      userStore
        .iphoneLogin(loginForm.value)
        .then(() => {
          router.push({ path: redirect.value || "/" });
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

getCookie();

const num = ref(0);
let timer = null;
//获取验证码
const giveCode = async () => {
  const PHONE = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
  clearInterval(timer);
  if (!loginForm.value.phoneNumber) return proxy.warningMsg("请填写手机号!");
  if (!PHONE.test(loginForm.value.phoneNumber)) {
    return proxy.warningMsg("手机号格式错误!");
  }
  try {
    Show.value = true;
  } catch {
  } finally {
  }
};

// 用户通过了验证
const success = async (msg) => {
  console.log("成功了");
  Show.value = false;
  //当通过了验证向后端发起请求获取验证码
  // const result = await getCodeAPI({
  //   phoneNumber: loginForm.phone
  // })
  num.value = 60;
  timer = setInterval(() => {
    num.value--;
    if (num.value == 0) clearInterval(timer);
  }, 1000);
  const res = await getCodeAPI({ phoneNumber: loginForm.value.phoneNumber });
};
// 用户点击遮罩层，应该关闭模态框
const close = () => {
  Show.value = false;
};
// 用户验证失败
const fail = () => {
  console.log("失败了");
  loading.value = false;
};
</script>

<style lang="scss" scoped>
.inputButton {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  .CodeButton {
    margin-left: 10px;
  }
}
.labelClass {
  width: 100%;
  border-bottom: 0.0625rem solid #c8c8c8;
  margin-bottom: 1.625rem;
}
.margin-bottom {
  margin-bottom: 2.75rem;
}
img {
  width: 1.75rem;
  height: 1.75rem;
}
.iponeimg {
  width: 2.5rem;
  height: 2.5rem;
}

.link-type {
  color: #4193fd;
  font-weight: 700;
}
</style>
